<template>
    <div>
        <Row class="button_row">
           <span style="float: left;">
                <Button type="primary" @click="handleAdd()"><Icon type="md-add-circle"/>录入</Button>&nbsp;
           </span>
        </Row>
        <Modal v-model="visible" :title="title" width="800" style="position:relative;">
            <Form ref="formData" :model="formData" :label-width="150" :rules="rules" :disabled="disableSubmit">
                <table style="width:100%;">
                    <tr>
                        <td>
                            <FormItem label="编号" prop="yjah0001">
                                <Input v-model="formData.yjah0001" style="width: 200px" placeholder="请输入编号"></Input>
                            </FormItem>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <FormItem label="标题" prop="yjah0002">
                                <Input v-model="formData.yjah0002" style="width: 200px" placeholder="请输入标题"></Input>
                            </FormItem>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <FormItem label="政策文件(必须为PDF)">
                                <template>
                                    <Upload
                                            action="/api/ac/hdplugin/ossService/uploadBase64"
                                            :before-upload="(file) => handleUploadNative(file)"
                                            :max-size=5120
                                            :accept="Accept"
                                            :on-exceeded-size="handleMaxSize">
                                        <Button icon="ios-cloud-upload-outline">上传政策文件</Button>
                                    </Upload>
                                    <div v-if="file !== null">
                                        {{ file.name }}
                                    </div>
                                </template>
                            </FormItem>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <FormItem label="发文时间" prop="yjah0003">
                                <DatePicker type="date" v-model="formData.yjah0003" placeholder="请选择发文时间"
                                            style="width: 200px"  :editable="false"></DatePicker>
                            </FormItem>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <FormItem label="是否首页" prop="yjah0005">
                                <dictSelect :sel_val='formData.yjah0005' dictCode="yesorno" placeholder="请选择是否首页"
                                            :bindData.sync="formData.yjah0005" style="width: 200px" clearable/>
                            </FormItem>
                        </td>
                    </tr>

                </table>
            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="visible = false,Loading=false">取消</Button>
                <template v-if="!disableSubmit">
                    <Button type="primary" size="large" @click="handleSubmit('formData')">确定</Button>
                </template>
            </div>
        </Modal>
        <div class="table_div">
            <Table :columns="columns" :data="tableData" :loading="Loading">
                <template slot-scope="{ row, record, index  }" slot="action">
                    <Button type="info" size="small" style="margin-right: 5px" @click="handleEdit(index)">编辑</Button>
                    <Button type="error" size="small" style="margin-right: 5px" @click="handleDelete(index)">删除</Button>
                    <Button type="success" size="small" style="margin-right: 5px" @click="handleDetail(index)">详情</Button>
                </template>
            </Table>
            <Page :total="dataCount" :page-size="pageSize" show-total class="paging"
                  @on-change="handleTableChange" :current="pageNo"></Page>
        </div>
    </div>
</template>

<script>
    import {postAction} from '@/api/request'
    import {CommonMixin} from '@/views/common/js/CommonMixin'
    import dictSelect from '@/components/dictSelect/dictSelect.vue'
    import DateFormat from '@/plugins/format.js'
    import {getSign, createUpLoadFiles, compressImg} from '@/api/common'

    export default {
        mixins: [CommonMixin],
        components: {
            dictSelect,
        },
        data() {
            return {
                file: null,
                loadingStatus: false,
                Accept: ".pdf",
                rules: {
                    yjah0001: [
                        {required: true, message: '请输入"编号"', trigger: 'blur'}
                    ],
                    yjah0002: [
                        {required: true, message: '请输入"标题"', trigger: 'blur'}
                    ],
                    yjah0003: [
                        {required: true, message: '请选择"发文时间"', trigger: 'blur', type: 'date'}
                    ],
                    yjah0005: [
                        {required: true, message: '请选择"是否首页"', trigger: 'blur'}
                    ],
                },
                fieldsToValidate: ["yjah0001", "yjah0002", "yjah0003", "yjah0005"],
                columns: [
                    {
                        title: '编号',
                        align: 'center',
                        key: 'yjah0001',
                        width: '250px'
                    },
                    {
                        title: '标题',
                        align: 'center',
                        key: 'yjah0002',
                        // width: 250
                    },
                    {
                        title: '发文时间',
                        align: 'center',
                        key: 'yjah0003',
                        width: '140px',
                        render: (h, params) => {
                            let value = params.row.yjah0003
                            if (typeof (value) === 'undefined' || value === null || value === '' || value === undefined) {
                                value = '--'
                            } else {
                                value = DateFormat(value, 'YYYY-MM-DD')
                            }
                            return h('span', value + ' ')
                        },
                    },
                    {
                        title: '是否首页',
                        align: 'center',
                        key: 'yjah0005_name',
                        width: 140
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center',
                        slot: 'action',
                        width: '200px',
                        fixed: 'right'
                    }
                ],
                disableSubmit: false,
                upPicData: {},
                searchInfo: "",
                tableData: [],
                Loading: false,
                url: {
                    list: "/api/ac/subsistence/ss02040Service/getPageList",
                    delete: "/api/ac/subsistence/ss02040Service/deleteData"
                },
                formData: {},
                processData: {},
                queryParam: {},
                visible: false,
                dataCount: 0,
                pageSize: 10,
                modal: false,
                title: "",
                uploadFileData: {},
            }
        },
        methods: {
            loadImg(response, file) {
                if (response.errcode == 0) {
                    this.formData.yjah0004 = response.data;
                } else {
                    this.$Message.error('上传失败！')
                }
                this.Loading = false;
            },
            handleMaxSize() {
                this.$Message.error("文件过大, 请将文件控制在5MB以下再上传")
            },
            handleAdd() {
                this.$refs['formData'].resetFields();
                let that = this;
                that.title = "花名册录入";
                that.disableSubmit = false;
                let record = {};
                that.visible = true;
                that.different = that.uuid();
                that.formData = Object.assign({}, record)
            },
            handleDetail(index) {
                let that = this;
                that.title = "详情";
                that.disableSubmit = true;
                let record = that.tableData[index];
                if (record.id) {
                    that.visible = true
                    that.formData = Object.assign({}, record);
                    that.formData.yjah0003 = DateFormat(that.formData.yjah0003, 'YYYY-MM-DD');
                } else {
                    that.visible = false
                }
            },
            handleEdit(index) {
                let that = this;
                that.disableSubmit = false;
                that.title = "救助政策文件编辑";
                let record = that.tableData[index];
                if (record.id) {
                    that.visible = true
                    that.formData = Object.assign({}, record);
                    that.formData.yjah0003 = DateFormat(that.formData.yjah0003, 'YYYY-MM-DD');
                } else {
                    that.visible = false
                }
            },
            handleDelete(index) {
                let that = this;
                this.$Modal.confirm({
                    title: '确定删除吗？',
                    onOk: () => {
                        if (!this.url.delete) {
                            this.$Message.error("请设置url.delete属性!")
                            return
                        }
                        postAction(that.url.delete, that.tableData[index]).then((res) => {
                            if (res.data.errcode == 0) {
                                //重新计算分页问题
                                that.reCalculatePage(1);
                                that.$Message.success("删除成功！");
                            } else {
                                that.$Message.error(res.data.errmsg);
                            }
                        });
                    }
                })
            },
            handleSubmit(name) {
                let that = this;
                let validate = true;
                let err_msg = [];
                for (let item of that.fieldsToValidate) {
                    that.$refs[name].validateField(item, (error) => {
                        if (error) {
                            validate = false;
                            err_msg.push(that.rules[item][0].message);
                        }
                    })
                }
                if (validate) {
                    let that = this;
                    that.Loading = true;
                    that.visible = false;
                    let url = "/api/ac/subsistence/ss02040Service/insertData";
                    if (that.formData.id) {
                        url = "/api/ac/subsistence/ss02040Service/updateData";
                    }
                    that.formData.yjah0003 = DateFormat(that.formData.yjah0003, 'YYYY-MM-DD')
                    postAction(url, that.formData).then((res) => {
                        if (res.data.errcode != 0) {
                            that.$Message.error(res.data.errmsg);
                        } else {
                            that.modalFormOk();
                            that.visible = false;
                        }
                    }).finally(() => {
                        that.Loading = false;
                    });
                } else {
                    that.$Message.error(err_msg[0]);
                    that.Loading = false;
                    return;
                }
            },
            async handleUploadNative(file) {
                // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
                // if (!isJpgOrPng) {
                //     this.$Message.error('只能上传JPG或PNG格式图片!');
                //     return false;
                // }
                // // 超过1M 压缩 图片为1M
                // var fileSize = file.size / 1024 / 1024
                // if (fileSize > 1 && fileSize < 2) {
                //     // 如果图片大于1M并且小于2M 那么压缩0.5
                //     file = await this.imageConversion(file, 0.5);
                // } else if (fileSize > 2) {
                //     file = await this.imageConversion(file, 0.2);
                // }
                var uploadBase64 = await
                    this.file2Base64(file);
                let index = uploadBase64.indexOf('base64,') + 7;
                uploadBase64 = uploadBase64.substring(index);
                var fileName = DateFormat(new Date(), 'YYYYMMDDhhmmss') + '.pdf';
                var filePath = 'subsistence/' + DateFormat(new Date(), 'YYYYMMDD') + '/';
                var timeStep = new Date().getTime().toString();
                let param = {
                    filePath: filePath,
                    fileName: fileName,
                    timestamp: timeStep
                };
                //获取签名
                var signData = await
                    getSign(param);
                var sign = signData.data.data.sign;
                if (fileName.length > 20) {
                    fileName = fileName.substring(0, 20) + '.png';
                }
                var uploadFileData = {
                    sign: sign,
                    filePath: filePath,
                    fileName: fileName,
                    timestamp: timeStep,
                    file: uploadBase64
                };
                this.uploadFileData = uploadFileData;
                postAction('/api/ac/subsistence/businessCommonService/upload', uploadFileData).then(res => {
                    this.loadImg(res.data, file);
                });
                return false;
            },
            file2Base64(file) {
                return new Promise((resolve, reject) => {
                    let reader = new FileReader();
                    let fileResult = "";
                    reader.readAsDataURL(file);
                    //开始转
                    reader.onload = function () {
                        fileResult = reader.result;
                    };
                    //转 失败
                    reader.onerror = function (error) {
                        reject(error);
                    };
                    //转 结束  咱就 resolve 出去
                    reader.onloadend = function () {
                        resolve(fileResult);
                    };
                });
            }
        },
        created() {
            this.loadData();
        },
    }
</script>
<style scoped>
    /deep/ .ivu-form-item-error-tip {
        display: none;
    }

    .ivu-form-item {
        margin-bottom: 0px;
    }

    .itemStyle {
        width: 180px
    }

    .head-img1 {
        height: 200px;
        width: 250px;
        margin-top: 15px;
    }

    .head-img {
        height: 200px;
        width: 250px;
    }

    .imgBackColor {
        background-color: WhiteSmoke;
        height: 250px;
    }

    .positiveTDiv {
        height: 240px;
        width: 75px;
        line-height: 240px;
        background-color: #7CCD7C;
        margin-bottom: 10px;
        color: white;
        font-size: 14px;
        font-weight: 700;
    }
</style>
